<?php

namespace app\common\service;

use app\common\model\ExpressDailyStats as ExpressDailyStatsModel;
use think\facade\Cache;

class ExpressDailyStats
{
    /**
     * 获取并递增序号（TP5缓存版）
     * @param int $companyCode 公司代码
     * @return int
     * @throws \Exception
     */
    public static function getAndIncSequence(int $companyCode)
    {
        $datePart = date('md');
        $cacheKey = 'warehouse_sequence_' . $companyCode . '_' . date('Ymd');

        // 1. 从缓存获取当前序号
        $sequence = Cache::get($cacheKey, 0) + 1;

        // 2. 更新缓存（有效期到当天23:59）
        $expire = strtotime('tomorrow') - time();
        Cache::set($cacheKey, $sequence, $expire);

        if($sequence % 100 !== 0) return $sequence;

        // 3. 异步更新数据库（实际项目可用队列）
        $eds = ExpressDailyStatsModel::where([
            'company_code' => $companyCode,
            'date_part' => $datePart,
        ])->find();
        if($eds !== false){
            $eds->total_count = $sequence;
            $eds->save();
            return $sequence;
        }

        $eds = new ExpressDailyStatsModel();
        $eds->save([
            'company_code' => $companyCode,
            'stat_date' => $datePart,
            'total_count' => $sequence,
        ]);
        return $sequence;
    }
}